package com.manster.security;

import cn.hutool.core.util.StrUtil;
import com.manster.entity.SysUser;
import com.manster.service.SysUserService;
import com.manster.util.Const;
import com.manster.util.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * 解析jwt
 * @Author manster
 * @Date 2022/3/14
 **/
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    UserDetailServiceImpl userDetailService;

    @Autowired
    SysUserService userService;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //jwt获取
        String jwt = request.getHeader(Const.HEADER);
        //没有就去进行登录，有则直接登录
        if(StrUtil.isBlankOrUndefined(jwt)){
            chain.doFilter(request, response);
            return;
        }
        Claims claim = JwtUtils.getClaimByToken(jwt);
        //判断是否有信息
        if (claim == null){
            throw new JwtException("token 异常");
        }
        //判断是否过期
        if(JwtUtils.isTokenExpired(claim)){
            throw new JwtException("token已过期");
        }
        //获取主题内容
        String username = claim.getSubject();
        //获取用户权限信息
        SysUser user = userService.getByUsername(username);

        UsernamePasswordAuthenticationToken token
                = new UsernamePasswordAuthenticationToken(username, null, userDetailService.getUserAuthority(user.getId()));

        //进行自动登录
        SecurityContextHolder.getContext().setAuthentication(token);
        user.setLastLogin(new Date());
        userService.updateById(user);

        chain.doFilter(request,response);
    }
}
